< previous page page_188 next page >

Page 188
Listing 9.4 INSTREX.ZIPUsing the InStr Function to Divide a String into Words
Sub PrintWords(stInput As String)
    Dim inCounter As Integer
    Dim inFoundPos As Integer

    Const PARSECHAR = " " 'Space

    'If string is blank then do nothing
    If Len(stInput) = 0 Then Exit Sub

    'Start at the first character
    inCounter = 1

    'Search for a space
    inFoundPos = InStr(inCounter, stInput, PARSECHAR)

    'If a space is found print the word and keep searching
    While inFoundPos <> 0
      Debug.Print Mid$(stInput, inCounter, inFoundPos - inCounter)
      inCounter = inFoundPos + 1
      inFoundPos = InStr(inCounter, stInput, PARSECHAR)
    Wend

    'Print the remainder of the string
    If inCounter < Len(stInput) Then
        Debug.Print Mid$(stInput, inCounter)
    End If
End Sub
The input and results of this code appear in Figure 9.5.
0188-01.jpg
Figure 9.5
Use 
InStr to find all the spaces in a string.
In Listing 9.4, notice that the InStr function searches from the first position in the string to the last. Visual Basic now includes a similar function called InstrRev to perform the search in the opposite direction. InstrRev works the same way as InStr, but the syntax is slightly different:
InstrRev(string1, string2[, start[, compare]])

 
< previous page page_188 next page >